package com.lego.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lego.bean.CommonResult;
import com.lego.bean.Goods;
import com.lego.service.impl.GoodsServiceImpl;

@WebServlet("/updateGoods.do")
public class UpdateGoodsServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		 GoodsServiceImpl gds = new GoodsServiceImpl();
		 resp.setContentType("application/json;charset=utf-8");
	        
	        // 1. 获取所有参数
	        int goodsId = Integer.parseInt(req.getParameter("goodsId"));
	        String goodsName = req.getParameter("goodsName");
	        int quantity = Integer.parseInt(req.getParameter("goodsNum"));  
	        double price = Double.parseDouble(req.getParameter("goodsPrice")); 
	        String goodsType = req.getParameter("goodsType");
	        
	        CommonResult result = new CommonResult();
	        ObjectMapper om = new ObjectMapper();
	        
	        Goods goods = new Goods();
	        goods.setGoodsId(goodsId);  // 设置商品ID
	        goods.setGoodsName(goodsName);
	        goods.setQuantity(quantity);
	        goods.setPrice(price);
	        goods.setGoodsType(goodsType);
	        
	        try {
	            int rows = gds.updateGoods(goods);
	            if (rows == 1) {
	                result.setCode(200);
	                result.setMessage("商品更新成功");
	                result.setData(goods);
	            } else {
	                result.setCode(500);
	                result.setMessage("商品更新失败");
	            }
	        } catch (Exception e) {
	            result.setCode(500);
	            result.setMessage("服务器错误: " + e.getMessage());
	        }
	        
	        // 3. 返回响应
	        resp.getWriter().write(om.writeValueAsString(result));
	}
}
